package com.backend.controller.rbac;

import com.backend.annotation.RequireRole;
import com.backend.service.rbac.RoleService;
import com.common.constant.MessageConstant;
import com.common.result.Result;
import com.pojo.dto.RoleDTO;
import com.pojo.dto.UpdateRoleNameDTO;
import com.pojo.entity.Role;
import com.pojo.vo.RoleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    RoleService roleService;
    /**
     * 添加一个角色
     */
    @PostMapping("/addRole")
    @RequireRole("admin")
    public Result addRole(@RequestBody RoleDTO roleDTO) {
        Boolean result = roleService.addRole(roleDTO);
        if (Boolean.FALSE.equals(result)) {
            return Result.error(MessageConstant.ADD_USER_FAIL);
        }
        return Result.success(MessageConstant.ADD_USER_SUCCESS);
    }
    /**
     * 通过角色名删除一个角色
     */
    @DeleteMapping("/removeRoleByUsername/{username}")
    @RequireRole("admin")
    public Result removeRoleByUsername(@PathVariable("username") String username) {
        Integer result = roleService.removeRoleByUsername(username);
        if (result == 0) {
            return Result.error(MessageConstant.REMOVE_USER_FAIL);
        }
        return Result.success(MessageConstant.REMOVE_USER_SUCCESS);
    }
    /**
     * 查询所有角色
     */
    @GetMapping("/getAllRoles")
    @RequireRole("admin")
    public Result getAllRoles() {
        List<Role> roles = roleService.getAllRoles();
        return Result.success(roles);
    }
    /**
     * 修改角色名或描述
     */
    @PutMapping("/updateRoleName")
    @RequireRole("admin")
    public Result updateRoleName(@RequestBody UpdateRoleNameDTO updateRoleNameDTO) {
        Integer result = roleService.updateRoleName(updateRoleNameDTO);
        if (result == 0) {
            return Result.error(MessageConstant.UPDATE_ROLE_NAME_FAIL);
        }
        return Result.success(MessageConstant.UPDATE_ROLE_NAME_SUCCESS);
    }
    /**
     * 修改该角色的状态
     */
    @PutMapping("/updateRoleStatus/{name}/{status}")
    @RequireRole("admin")
    public Result updateRoleStatus(@PathVariable("name") String name, @PathVariable("status") Integer status) {
        Integer result = roleService.updateRoleStatus(name, status);
        if (result == 0) {
            return Result.error(MessageConstant.UPDATE_ROLE_STATUS_FAIL);
        }
        return Result.success(MessageConstant.UPDATE_ROLE_STATUS_SUCCESS);
    }
    /**
     * 通过角色名查询角色信息
     */
    @GetMapping("/getRoleByName/{name}")
    @RequireRole("admin")
    public Result getRoleByName(@PathVariable("name") String name) {
        RoleVO roleVO = roleService.getRoleByName(name);
        return Result.success(roleVO);
    }
}
